//
//  ViewController.m
//  YiDingShopping
//
//  Created by 欧腾 on 2017/8/22.
//  Copyright © 2017年 outeng. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "SVProgressHUD.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "WebViewJavascriptBridge.h"
#define Width   self.view.bounds.size.width
#define Height  self.view.bounds.size.height

@protocol JSObjcDelegate <JSExport>
- (void)call;
- (void)getCall:(NSString *)callString;

@end
@interface ViewController ()<WKNavigationDelegate,JSObjcDelegate,WKUIDelegate,WKScriptMessageHandler,UIWebViewDelegate>
@property (nonatomic, strong) JSContext *jsContext;
@property(nonatomic,strong) WKWebView *webView;
@property(nonatomic,strong)UIWebView *webViews;

@property WebViewJavascriptBridge* bridge;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    WKWebViewConfiguration*config = [[WKWebView.Configuration alloc]init];
//    config.selectionGranularity = WKSelectionGranularityCharacter;
//    WKWebView  *webView= [[WKWebViewalloc]initWithFrame:CGRectZero configuration:config];
//    作者：timelessg
//    链接：http://www.jianshu.com/p/6d76bba83f94
//    來源：简书
//    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

    [SVProgressHUD show];
//    [self loadWKWebView];
    [self loaduiWebView];
}

- (void)loaduiWebView
{
    _webViews =[[UIWebView alloc] initWithFrame:CGRectMake(0, 20, Width, Height-20)];
    _webViews.delegate = self;
    // _webView.
    //    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, Width, Height-20)];
    //    _webView.delegate = self;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    [_webViews loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://hzydshop.com/mobile/index.php?version=%@",app_build]]]];
    _webViews.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_webViews];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
    NSLog(@"页面加载完成");
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];

    NSString *str1 = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"check_version(%@);",app_build]];
    //    NSLog(@"JS返回值：%@",str1);
    NSString *str2 =[NSString stringWithFormat:@"JS返回值：%@",str1];
    
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    //定义好JS要调用的方法, share就是调用的share方法名
    context[@"testobject"] = ^() {
        NSLog(@"+++++++Begin Log+++++++");
        NSArray *args = [JSContext currentArguments];

        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
            [alertView show];
        });

        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }

        NSLog(@"-------End Log-------");
    };
    context[@"testobject"] = self;
    //首先创建JSContext对象（此处通过当前webView的键获取到jscontext）
    
//    _context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    
    
    //第二种情况，js是通过对象调用的，我们假设js里面有一个对象 testobject 在调用方法
    
    //首先创建我们新建类的对象，将他赋值给js的对象
    
//    TestJSObject *testJO=[TestJSObject new];
//
//    testJO.showPickerBlock = ^{
//
//        [selfshowImagePicker];
//
//    };
//
//    _context[@"testobject"]=testJO;
}

#pragma mark- UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL * url = [request URL];
    NSLog(@"%@",[url scheme]);
    if ([[url scheme] isEqualToString:@"update"]) {
        NSArray *params =[url.query componentsSeparatedByString:@"&"];
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        for (NSString *paramStr in params) {
            NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
            if (dicArray.count > 1) {
                NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [tempDic setObject:decodeValue forKey:dicArray[0]];
            }
        }
        [self update];
        return NO;
    }
    return YES;
}

-(void)loadWKWebView
{
    _webView =[[WKWebView alloc] initWithFrame:CGRectMake(0, 20, Width, Height-20)];
    _webView.UIDelegate=self;
   // _webView.
//    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, Width, Height-20)];
//    _webView.delegate = self;
    _webView.navigationDelegate = self;
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://hzydshop.com/mobile/"]]];
    _webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_webView];

    //@"http://hzydshop.com/mobile/"
    //    [self.webView.configuration.userContentController  addScriptMessageHandler:self name:@"check_version"];
    
    WKUserContentController *userCC = self.webView.configuration.userContentController;
    //JS调用OC 添加处理脚本
    [userCC addScriptMessageHandler:self name:@"check_version"];
//    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView];
//    [_bridge setWebViewDelegate:self];
//
//    [_bridge registerHandler:@"check_version" handler:^(id data, WVJBResponseCallback responseCallback) {
//        NSLog(@"testObjcCallback called: %@", data);
//        responseCallback(@"Response from testObjcCallback");
//    }];
//
//
//    [_bridge callHandler:@"check_version" data:@{ @"foo":@"before ready" }];
    
}



#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {

    

}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [SVProgressHUD dismiss];
    NSLog(@"页面加载完成");
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    // app build版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];

    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"check_version(%@)",app_Version] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@ %@",response,error);
    }];
}


- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
  
    NSLog(@"%@",defaultText);
    
}
//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    [SVProgressHUD dismiss];
//    NSLog(@"页面加载完成");
//
//    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    self.jsContext[@"check_version"] = self;
//    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
//        context.exception = exceptionValue;
//        NSLog(@"异常信息：%@", exceptionValue);
//    };
//}

//- (void)check_version{
//    NSLog(@"call");
//}
//
//
- (void)update
{
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"12312" message:@"123" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//    [alert show];、
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/%E4%B8%80%E9%BC%8E%E8%B4%AD%E7%89%A9/id1273959771?l=zh&ls=1&mt=8"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
